package net.cmkj.mine.bean;

import com.jfinal.aop.Before;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import net.cmkj.mine.bean.base.BaseModules;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.util.BeanUtils;
import net.cmkj.mine.util.CommonUtils;
import net.cmkj.mine.util.FileUtlis;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Modules extends BaseModules<Modules> {

	public static final Modules dao = new Modules().dao();
	
	private static Logger log = LogManager.getLogger(Modules.class);

    private String table = PropKit.use("table.txt").get("table");
	
	/**
	 * 获取列表
	 * @param pageNumber
	 * @param pageSize
	 * @param name
	 * @param status
	 * @return
	 */
	public Page<Modules> paginate(int pageNumber, int pageSize, String table, String name, Integer status, String orderbyStr) throws Exception {
		log.info("获取列表");
		List<Object> params = new ArrayList<Object>();
		StringBuffer sqlExceptSelect=new StringBuffer(" from modules t LEFT JOIN sys_user u on t.createuser = u.id where 1=1 ");
		if(CommonUtils.isNotEmpty(name)){
			sqlExceptSelect.append(" and t.name like ? ");
			params.add("%"+name+"%");
		}
		if(status != null){
			sqlExceptSelect.append(" and t.status = ? ");
			params.add(status);
		}
		sqlExceptSelect.append(" "+orderbyStr);
		return dao.paginate(pageNumber, pageSize, "SELECT t.*, concat('"+table+"', t.tablename) as wholetablename ,u.username ", sqlExceptSelect.toString(), CommonUtils.listToArr(params));
	}
	
	/**
	 * 获取对象
	 * @param id
	 * @return
	 */
	public Modules findById(long id) throws Exception {
		log.info("获取对象");
		return dao.findFirst("select t.*, concat('"+table+"', t.tablename) as wholetablename from modules t where t.id = ?", id);
	}

	/**
	 * 获取最终模版
	 * @return
	 * @throws Exception
	 */
	public Modules getLastModule() throws Exception {
		return dao.findFirst("select t.* from modules t order by t.id desc limit 0, 1");
	}

	/**
	 * 根据访问路径获取模块
	 * @param url
	 * @param table
	 * @return
	 * @throws Exception
	 */
	public Modules getModuleByUrl(String url, String table) throws Exception {
		return dao.findFirst("select t.*, concat('"+table+"', t.tablename) as wholetablename from modules t where t.url = ?", url);
	}

	/**
	 * 对象保存
	 * @param model
	 * @return
	 */
	@Before(Tx.class)
	public boolean save(Modules model, SysUser user) throws Exception {
		log.info("对象保存");
	    boolean flag = false;
		if (null == model.getId()) {
			flag = model.setCreatedate(new Date()).setCreateuser(user.getId()).save();
		} else {
			Modules src = model.findById(model.getId());
			log.info(BeanUtils.compare(src, model));
			flag = model.update();
		}
        SysRes.dao.getSysResList(new ArrayList<SysRes>(), user.getId(),1);
        SysRes.dao.getSysUserMenuView( new StringBuffer(),user.getId());
		return flag;
	}
	
	/**
	 * 对象删除
	 * @param ids
	 * @return
	 */
	@Before(Tx.class)
	public InvokeResult deleteByIds(String ids,SysUser user) throws Exception{
		log.info("对象删除");
    	String idarr[] = ids.split(",");
    	for (String id : idarr) {
            String tablename = dao.findById(id).getTablename();
            Integer sysres = dao.findById(id).getSysres();
            if (!dao.findById(id).delete()) {
    			log.error("批量删除失败！");
    			throw new RuntimeException(id+"批量删除失败");
    		}else{
                Columns.dao.deleteByModuleid(id);
                SysRes.dao.deleteByIds(sysres);
                SysRes.dao.deleteByPid(sysres);
                Columns.dao.deleteFileTable(table+tablename);
                Columns.dao.deleteTable(table+tablename);
                String path = PathKit.getWebRootPath()+"/upload/"+table+tablename;
                FileUtlis.deleteFileAll(path);
			}
    	}
        SysRes.dao.getSysResList(new ArrayList<SysRes>(), user.getId(),1);
        SysRes.dao.getSysUserMenuView( new StringBuffer(),user.getId());
    	return InvokeResult.success();
	}
	/**
	 * 修改对象状态
	 * @param ids
	 * @return
	 */
	@Before(Tx.class)
	public InvokeResult setStatus(String ids, Integer status,SysUser user) throws Exception{
		log.info("对象状态变更");
		String idarr[] = ids.split(",");
    	for(String id : idarr){
    		if (!dao.findById(id).set("status", status).update()) {
    			log.error("对象批量状态变更失败！");
    			throw new RuntimeException(id+"状态批量变更失败！");
    		}
		}
        SysRes.dao.getSysResList(new ArrayList<SysRes>(), user.getId(),1);
        SysRes.dao.getSysUserMenuView( new StringBuffer(),user.getId());
		return InvokeResult.success();
	}

	/**
	 * 获取关联表单列表
	 * @param moduleid
	 * @return
	 * @throws Exception
	 */
	public List<Modules> getForeignTables(Long moduleid) throws Exception {
		if (moduleid != null) {
			return dao.find("select t.* from modules t where t.status = 1 and t.id != ? order by t.id", moduleid);
		} else {
			return dao.find("select t.* from modules t where t.status = 1 order by t.id");
		}
	}
	@Before(Tx.class)
	public InvokeResult setIsInterface(String id, Integer status) throws Exception{
		log.info("对象接口状态变更");
		if (!dao.findById(id).set("is_interface", status).update()) {
			log.error("对象批量状态变更失败！");
			throw new RuntimeException(id+"状态批量变更失败！");
		}
		return InvokeResult.success();
	}
}